package com.study.common.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * 为了实现事务而存在
 * 默认spring创建一个单实例
 *
 * @author: chenhs
 * @date: Created in 16:48 2019/11/19
 **/
@Component
public class MyTransactionManager {

    @Autowired
    DataSource dataSource;

    /**
     * 一个对象 一个值， 被共享
     */
    ThreadLocal<Connection> currentConnection = new ThreadLocal<>();

    public Connection getConnection() throws SQLException {
        if (currentConnection.get() == null) {
            currentConnection.set(dataSource.getConnection());
        }
        return currentConnection.get();
    }


    public void releaseConnection(Connection connection) throws SQLException {
        if (connection == null) {
            return;
        }
        connection.close();

        if (currentConnection.get() == null) {
            return;
        }
        currentConnection.remove();
    }
}
